package gl.java.umsp.protocol;

import gl.java.umsp.Umsp;
import gl.java.umsp.UmspConfig;
import gl.java.umsp.UmspHeader;
import gl.java.umsp.bean.Match;
import gl.java.umsp.bean.User;
import gl.java.umsp.event.Event;
import gl.java.umsp.event.EventPublisher;
import gl.java.umsp.router.ChannelRouter;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class GateWayHandleMatch implements IUmspHandler {
    @Override
    public boolean handle(ChannelHandlerContext ctx, UmspHeader msg) {
        if (Umsp.CMD_MATCH == msg.cmd) {
            //查找用户信息
            Integer userID = ChannelRouter.getInstance().getID(ctx.channel());
            if (userID != 0) {
                Match match = Match.fromJson(new String(msg.payload), Match.class);
                match.setWantToMatchUser(User.getUserInfo(userID));
                String event = Event.CHANNEL_MATCH_EVENT + UmspConfig.LINK_CHAR_KEY + match.getWantToMatchUser().gameID + UmspConfig.LINK_CHAR_KEY + match.getMatchServiceIndex();
                EventPublisher.pub(event, match.toString());
                return true;
            } else {
                log.warn("user is not login:" + ctx.channel());
            }
        }
        return false;
    }

    private int getMatchServiceIndex(UmspHeader msg, User userInfo) {
        //TODO 分居匹配服务的状态使用更加友好的服务分配算法
        return msg.serviceID;
    }


}
